// https://leetcode.cn/problems/reverse-nodes-in-k-group/?envType=study-plan-v2&envId=top-interview-150

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverse(ListNode* head) {
        if (head == nullptr || head->next == nullptr) {
            return head;
        }

        ListNode* p = reverse(head->next);
        head->next->next = head;
        head->next = nullptr;
        return p;
    }

    ListNode* reverseKGroup(ListNode* head, int k) {
        if (k == 1) {
            return head;
        }

        ListNode* dummy = new ListNode(0, head);
        ListNode* prev = dummy;
        ListNode* cur = head;
        int len = 0;
        while (cur) {
            len++;
            cur = cur->next;
        }

        int n = len / k;
        cur = head;
        for (int i = 0; i < n; i++) {
            ListNode* leftNode = cur;
            for (int j = 0; j < k - 1; j++) {
                cur = cur->next;
            }
            ListNode* tail = cur->next;
            cur->next = nullptr;

            ListNode* reversedNode = reverse(leftNode);
            leftNode->next = tail;
            prev->next = reversedNode;
            prev = leftNode;
            cur = tail;
        }

        return dummy->next;
    }
};